const express = require("express");
const moment = require("moment");
const db = require("../modules/DBHelper");

const AccountRouter = express.Router();

//登录
AccountRouter.post("/login", async (req, res, next) => {
    //1.接受前端发送过来的数据
    var oUser = req.body;
    //2. 准备sql语句
    let sql_login = "SELECT `uId`,`uname`,`create`,`usex`,`ustatus` FROM `userinfo`"
    sql_login += " WHERE `uname`=? AND `upwd`=? AND `ustatus`=1;";
    //3.准备与sql语句对应的参数
    let params = [
        oUser.name,
        oUser.pwd
    ]
    let results = await db.execute(sql_login, params);
    var isLogin = results.length >= 1;
    //根据结果进行响应提示
    if (isLogin) {
        res.json({
            msg: "登录成功!",
            code: 200,
            data: results[0]
        })
    } else {
        res.json({
            msg: "登录失败!",
            code: 401 // 请求要求用户的身份认证
        })
    }
})
//注册
AccountRouter.post("/register", async (req, res, next) => {
    //1.得到前端发送过来的数据
    const oUser = req.body;
    //2.准备sql语句
    let sql_reg = "INSERT INTO `userinfo` (`uname`,`upwd`,`usex`,`create`)VALUES(?,?,?,?);";
    //3.参数
    let params = [
        oUser.name,
        oUser.pwd,
        oUser.sex,
        moment().format("YYYY-MM-DD HH:mm:ss")
    ]


    //模拟延迟时间
    setTimeout( async () => {
        try {
            //4.执行sql.判断结果
            // 增删查改, 除了查询返回是一个数组,另外(增删改)返回受影响行数的状态
            // affectedRows 受影响行数
            let result = await db.execute(sql_reg, params);
            let isReg = result && result.affectedRows >= 1;
            res.json({
                msg: isReg ? "注册成功!" : "注册失败",
                code: 200
            })
        } catch (error) {
            res.json({
                msg: "注册失败",
                code: -200,
                error
            })
        }
    }, 2000);
})






module.exports = AccountRouter
